package com.yonyou.pmclouds.basecom.shiro.realm;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.yonyou.pmclouds.basecom.util.SDKUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.iuap.tenant.sdk.RoleAppCenter;
import com.yonyou.iuap.tenant.sdk.RoleCenter;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PMCloudsShiroRealm extends AuthorizingRealm {

	/*
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		ObjectMapper jsonMapper = new ObjectMapper();
		Set<String> permissions = SDKUtil.findYhtAuth();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(permissions);
		return info;
	}

	/*
	 * 登录验证 交给yhtfilter处理，所以这里全部是认证成功
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		return new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), getName());
	}

	/**
	 * 权限缓存去掉，因为缓存有工作台提供，工作台修改缓存后我们不知道如何涮新shiro缓存
	 * 但是前提条件是工作台提供缓存机制
	 */
	protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {

		if (principals == null) {
			return null;
		}
		AuthorizationInfo info = doGetAuthorizationInfo(principals);
		return info;
	}

}